/*
 * SalesReportAction.java
 *
 * Created on June 20, 2002, 6:23 PM
 */

package com.scalar.chiptrack.sales.actions;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Map;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;
import org.apache.poi.ss.usermodel.Workbook;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.utils.ExcelUtils;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.process.FinishedGoods;
import com.scalar.chiptrack.operations.process.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.reports.dao.DataDumpReportsDAO;
import com.scalar.chiptrack.sales.Customer;
import com.scalar.chiptrack.sales.forms.SalesReportForm;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.NewCustomerDAO;
import com.scalar.chiptrack.sales.dao.NewSalesOrderDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.users.User;


/**
 *
 * @author  Raj Vallamsetla
 * @version 1.0
 */
public class SalesReportAction extends ChipTrackAction
{
    private static final String ACTION_NAME = "/salesReport.do";

    public ActionForward execute( ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response )
            throws Exception
    {

        String action = request.getParameter( "action" );
        HttpSession session = request.getSession();
        SalesReportForm reportForm = (SalesReportForm) form;
        User user = ( User ) session.getAttribute( SessionKeys.USER_KEY );
        Workbook workbook = null;
        String fileName = "";
        if( user == null )
        {
            session.setAttribute( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString() );
            return ( mapping.findForward( "login" ) );
        }

        try
        {
            ArrayList<FinishedGoods> mktgPartNumberList = FinishedGoodsDAO.loadFinishedGoods();

            ArrayList customerSelectList = CustomerDAO.getAllCustomerNamesByUserType (null,user);
            request.setAttribute( "customerSelectList", customerSelectList );
            request.setAttribute( "endCustomerList", NewCustomerDAO.loadAllEndCustomersWithSOEndcustomersByUserType(null,-1,false,user) );
            request.setAttribute( "endUserList", NewCustomerDAO.loadAllEndUsersByUserType(null,-1, false,user) );

            if ("bbbReport".equalsIgnoreCase(action) )
            {
                ArrayList<LabelValueBean> fgLabelValuebeanList = new ArrayList<LabelValueBean>();
                FinishedGoods finishedGoods = null;

                for( int i = 0; i < mktgPartNumberList.size(); i++ )
                {
                    finishedGoods = ( FinishedGoods ) mktgPartNumberList.get( i );
                    fgLabelValuebeanList.add( new LabelValueBean( finishedGoods.getManufacturingPartNo(), finishedGoods.getProductId()+"" ) );
                }
                request.setAttribute( "fgLabelValuebeanList", fgLabelValuebeanList );
                request.setAttribute( "regionList", CustomerDAO.getAllRegionNameList() );
                request.setAttribute( "repOfficeList", NewCustomerDAO.getAllRepOfficesFromSalesOrderList() );
                request.setAttribute( "salesPersonList", SalesOrderDAO.getAllSalesPersonsListByUserType(null, user) );

                return ( mapping.findForward( "bbbReport" ) );
            }
            else if ("bbbReportXls".equalsIgnoreCase( action ) )
            {
                Map<String, String> paramMap = new HashMap<String, String>();
                paramMap.put ( "productId", reportForm.getProductIds() );
                paramMap.put ( "customerId", reportForm.getCustomerId()+"" );
                paramMap.put ( "salesPerson", reportForm.getSalesPerson() );
                paramMap.put ( "fromDate", reportForm.getFromDate() );
                paramMap.put ( "toDate", reportForm.getToDate() );
                paramMap.put ( "orderType", reportForm.getOrderType()+"" );
                paramMap.put ( "reportType", "XLREPORT" );
                paramMap.put ( "region", reportForm.getRegion());
                paramMap.put ( "regionRep", reportForm.getRegionRep() );
                paramMap.put ( "endUser", reportForm.getEndUser() );
                paramMap.put ( "endCustomer", reportForm.getEndCustomer() );

               workbook = NewCustomerDAO.loadBBBReprot ( null, paramMap );
               fileName = "BBBReport_" + DateUtil.getTimeStamp() ;
               ExcelUtils.generateExcelReport( workbook, fileName, response );
            }
            else
            {

                //ArrayList mktgPartNumberSelectList = new ArrayList();
                request.setAttribute( "mktgPartNumberSelectList", mktgPartNumberList );

                String baseProductId = request.getParameter("baseproductID");
                int baseProductIdInt = 0;
                if ( action.equals( "agedbacklogreport" ) )
                {
                    request.setAttribute( "endUsersWithEndUserIds", NewSalesOrderDAO.loadEndUsersWithEndUserIds() );
                }
                if ( baseProductId != null && action.equals( "agedbacklogreport" ) )
                {
                    try
                    {
                        baseProductIdInt = Integer.parseInt( baseProductId );
                    }
                    catch( NumberFormatException nfe ){}

                    ArrayList fgproductList = ProductDao.loadAllFGProductsByBaseProductId( baseProductIdInt );
                    /*for( int i = 0; i < fgproductList.size(); i++ )
                    {
                        finishedGoods = ( FinishedGoods ) fgproductList.get( i );
                        fgproductSelectList.add( finishedGoods );
                    }*/

                    request.setAttribute( "fgproductSelectList", fgproductList );
                }
                else
                {
                    request.setAttribute( "fgproductSelectList", new ArrayList() );
                }


                ArrayList regionList = CustomerDAO.getAllRegionNames();
                request.setAttribute( "regionList", regionList );
                ArrayList repOfficeList = NewCustomerDAO.getAllRepOfficesFromSalesOrder();
                request.setAttribute( "repOfficeList", repOfficeList );
                ArrayList salesPersonList = SalesOrderDAO.getAllSalesPersonsByUserType (null,user);

                request.setAttribute( "endCustomerList", NewCustomerDAO.loadAllEndCustomersWithSOEndcustomersByUserType(null,-1,false,user) );
                request.setAttribute( "endUserList", NewCustomerDAO.loadAllEndUsersByUserType(null,-1, false,user) );
                request.setAttribute( "salesPersonList", salesPersonList );

                ArrayList baseProductList = ProductDao.loadAllBaseProducts( null );
                request.setAttribute( "baseProductList", baseProductList );

                request.setAttribute( "quarterList", loadQuarterList() );
                request.setAttribute( "currentQtr", getCurrentQuarter() );
                request.setAttribute( "years", SalesOrderDAO.getYearList () );
                request.setAttribute( "fgiProducts", FinishedGoodsDAO.loadAllFGIProducts() );
            }
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }

        if( action.equals( "salesreport" ) )
        {
            return ( mapping.findForward( "salesreport" ) );
        }

        if( action.equals( "performancereport" ) )
        {
            return ( mapping.findForward( "performancereport" ) );
        }

        if( action.equals( "shippingreport" ) )
        {
            return ( mapping.findForward( "shippingreport" ) );
        }

        if( action.equals( "backlogreport" ) )
        {
            return ( mapping.findForward( "backlogreport" ) );
        }

        if( action.equals( "missedorderreport" ) )
        {
            return ( mapping.findForward( "missedorderreport" ) );
        }

        if( action.equals( "cobacklogreport" ) )
        {
            return ( mapping.findForward( "cobacklogreport" ) );
        }

        if( action.equals( "shipmentreport" ) )
        {
            return ( mapping.findForward( "shipmentreport" ) );
        }

        if( action.equals( "shipmentsummaryreport" ) )
        {
            return ( mapping.findForward( "shipmentsummaryreport" ) );
        }

        if( action.equals( "revenuereportbyproduct" ) )
        {
            return ( mapping.findForward( "revenuereportbyproduct" ) );
        }

        if( action.equals( "agedbacklogreport" ) )
        {
           return ( mapping.findForward( "agedbacklogreport" ) );
        }
        return null;
    }

    public ArrayList loadQuarterList()
    {
        int start_qtr = 1;
        int end_qtr = 4;

        ArrayList quarterList = new ArrayList ();
        for ( int quarter = start_qtr; quarter <= end_qtr; quarter++ )
        {
            quarterList.add ( new LabelValueBean ( "Qtr " + quarter, quarter + "") );
        }
        quarterList.add( new LabelValueBean ( "All", "All") );

        return quarterList;
    }

    private String getCurrentQuarter()
    {
        String qtr = "1";
        Calendar c = Calendar.getInstance();
        int month = c.get( Calendar.MONTH );

        if( month > 8 )
        {
            qtr = "4";
        }
        else if( month > 5 )
        {
            qtr = "3";
        }
        else if( month > 2 )
        {
            qtr = "2";
        }
        else
        {
            qtr = "1";
        }

        return qtr;
    }
}
